<template>
  <div class="app-container">
    <!--对象搜索树型列表-->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="product">
        <y-select
          v-model="queryParams.product"
          placeholder="请选择产品名称"
          :optionsFunc="listProduct"
        />
      </el-form-item>
      <el-form-item label="模块名称" prop="module">
        <y-tree-select
          v-model="queryParams.module"
          placeholder="请选择所属模块"
          :optionsFunc="selectModule"
          :optionsParams="{
            product: queryParams.product,
          }"
        />
      </el-form-item>
      <el-form-item label="需求名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入需求名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="需求分类" prop="classify">
        <y-select
          v-model="queryParams.classify"
          placeholder="请选择需求分类"
          :options="pms_req_classify"
        />
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <y-select
          v-model="queryParams.priority"
          placeholder="请选择优先级"
          :options="sys_priority_level"
        />
      </el-form-item>
      <el-form-item label="需求状态" prop="status">
        <y-select
          v-model="queryParams.status"
          placeholder="请选择需求状态"
          :options="pms_req_status"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--对象操作-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pms:requirement:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleEdit"
          v-hasPermi="['pms:requirement:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pms:requirement:delete']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['pms:requirement:import']"
          >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <y-export
          :url="'pms/requirement/export/'"
          :ids="ids"
          :filename="'requirement_data'"
          v-hasPermi="['pms:requirement:export']"
        />
      </el-col>
      <y-right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      />
    </el-row>

    <!--对象列表-->
    <el-table
      ref="tableRef"
      v-loading="loading"
      row-key="id"
      :data="requirementList"
      @selection-change="handleSelectionChange"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      border
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        reserve-selection
      />
      <el-table-column label="序号" width="100" align="center" type="index">
        <template #default="scope">
          {{ scope.$index + (queryParams.page - 1) * queryParams.limit + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="需求编号"
        min-width="300"
        align="center"
        prop="id"
        v-if="columns[0].visible"
        :show-overflow-tooltip="true"
        sortable
      />
      <el-table-column
        label="需求名称"
        align="center"
        min-width="300"
        prop="name"
        v-if="columns[1].visible"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <router-link
            :to="'/pms/requirement-info/index/' + scope.row.id"
            class="link-type"
          >
            <span>{{ scope.row.name }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        label="所属产品"
        min-width="180"
        align="center"
        prop="product_name"
        v-if="columns[2].visible"
        :show-overflow-tooltip="true"
        sortable
      />
      <el-table-column
        label="所属模块"
        width="120"
        align="center"
        prop="module_name"
        v-if="columns[3].visible"
        :show-overflow-tooltip="true"
        sortable
      />
      <el-table-column
        label="需求来源"
        width="120"
        align="center"
        prop="origin"
        v-if="columns[4].visible"
        :show-overflow-tooltip="true"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="pms_req_origin" :value="scope.row.origin" />
        </template>
      </el-table-column>
      <el-table-column
        label="需求分类"
        width="120"
        align="center"
        prop="classify"
        v-if="columns[5].visible"
        :show-overflow-tooltip="true"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="pms_req_classify" :value="scope.row.classify" />
        </template>
      </el-table-column>
      <el-table-column
        label="优先级"
        width="100"
        align="center"
        prop="priority"
        v-if="columns[6].visible"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <y-dict-tag
            :options="sys_priority_level"
            :value="scope.row.priority"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="用例数"
        width="100"
        align="center"
        prop="cases_count"
        v-if="columns[7].visible"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <router-link
            :to="`/tms/testcase/?reqs=${scope.row.id}`"
            class="link-type"
          >
            <span>{{ scope.row.cases_count }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        label="缺陷数"
        width="100"
        align="center"
        prop="bugs_count"
        v-if="columns[8].visible"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="需求状态"
        align="center"
        width="120"
        prop="status"
        v-if="columns[9].visible"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="pms_req_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="评审结果"
        align="center"
        width="120"
        prop="review_result"
        v-if="columns[10].visible"
        sortable
      >
        <template #default="scope">
          <y-dict-tag
            :options="pms_req_review"
            :value="scope.row.review_result"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="关闭类型"
        align="center"
        width="120"
        prop="closed_type"
        v-if="columns[11].visible"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="pms_req_close" :value="scope.row.closed_type" />
        </template>
      </el-table-column>
      <el-table-column
        label="负责人"
        width="120"
        align="center"
        prop="owner_name"
        v-if="columns[12].visible"
        sortable
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="创建人"
        width="120"
        align="center"
        prop="creator_name"
        v-if="columns[13].visible"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="create_time"
        v-if="columns[14].visible"
        width="160"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" align="center" width="250">
        <template #default="scope">
          <el-tooltip :content="editButtonContent(scope.row)" placement="top">
            <el-button
              :disabled="isEditButtonDisabled(scope.row)"
              link
              type="primary"
              icon="Edit"
              @click="handleEdit(scope.row)"
              v-hasPermi="['pms:requirement:edit']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip :content="reviewButtonContent(scope.row)" placement="top">
            <el-button
              :disabled="isReviewButtonDisabled(scope.row)"
              link
              type="primary"
              icon="Select"
              @click="handleReview(scope.row)"
              v-hasPermi="['pms:requirement:review']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip :content="changeButtonContent(scope.row)" placement="top">
            <el-button
              :disabled="isChangeButtonDisabled(scope.row)"
              link
              type="primary"
              icon="Switch"
              @click="handleChange(scope.row)"
              v-hasPermi="['pms:requirement:change']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            :content="bindingCaseButtonContent(scope.row)"
            placement="top"
          >
            <el-button
              :disabled="isBindingCaseButtonDisabled(scope.row)"
              link
              type="primary"
              icon="Connection"
              @click="handleBindingCase(scope.row)"
              v-hasPermi="['pms:requirement:edit']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.status != 'closed'"
            :content="closeButtonContent(scope.row)"
            placement="top"
          >
            <el-button
              :disabled="isCloseButtonDisabled(scope.row)"
              link
              type="primary"
              icon="SwitchButton"
              @click="handleClose(scope.row)"
              v-hasPermi="['pms:requirement:close']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.status === 'closed'"
            content="激活"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="MagicStick"
              @click="handleActive(scope.row)"
              v-hasPermi="['pms:requirement:active']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip :content="deleteButtonContent(scope.row)" placement="top">
            <el-button
              :disabled="isDeleteButtonDisabled(scope.row)"
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['pms:requirement:delete']"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--列表分页-->
    <y-pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <au-req
      :id="id"
      v-model="openAuReq"
      :title="title"
      :operate="operate"
      :getMethod="getRequirement"
      :addMethod="addRequirement"
      :updateMethod="updateRequirement"
      @submited="submited"
      @close="openAuReq = false"
    >
    </au-req>

    <!-- 选择评审人对话框 -->
    <reviewer-select
      :id="id"
      v-model="openRsReq"
      :title="title"
      :getMethod="getRequirement"
      :updateMethod="updateRequirement"
      @submited="submited"
      @close="openRsReq = false"
    >
    </reviewer-select>

    <!-- 开始评审对话框 -->
    <req-review
      :id="id"
      v-model="openReReq"
      :title="title"
      :getMethod="getRequirement"
      :updateMethod="updateRequirement"
      @submited="submited"
      @close="openReReq = false"
    >
    </req-review>

    <!-- 关闭需求对话框 -->
    <req-close
      :id="id"
      v-model="openClReq"
      :title="title"
      :getMethod="getRequirement"
      :updateMethod="updateRequirement"
      @submited="submited"
      @close="openClReq = false"
    >
    </req-close>

    <!-- 添加用例对话框 -->
    <ad-cases
      :id="id"
      v-model="openAdCases"
      :title="title"
      :getMethod="getRequirement"
      :updateMethod="updateRequirement"
      @submited="submited"
      @close="openAdCases = false"
    >
    </ad-cases>

    <!-- 导入对话框-->
    <y-import :upload="upload" @submited="submited" />
  </div>
</template>

<script setup name="ReqList">
import { listProduct } from "@/api/pms/product";
import { treeselect as selectModule } from "@/api/pms/module";
import {
  listRequirement,
  getRequirement,
  addRequirement,
  updateRequirement,
  delRequirement,
} from "@/api/pms/requirement";
import AuReq from "./components/AuReq";
import AdCases from "./components/AdCases";
import ReqClose from "./components/ReqClose";
import ReqReview from "./components/ReqReview";
import ReviewerSelect from "./components/ReviewerSelect";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const {
  pms_req_status,
  sys_priority_level,
  pms_req_origin,
  pms_req_classify,
  pms_req_review,
  pms_req_close,
} = proxy.useDict(
  "pms_req_status",
  "sys_priority_level",
  "pms_req_origin",
  "pms_req_classify",
  "pms_req_review",
  "pms_req_close"
);

const route = useRoute();

const id = ref(null);
const ids = ref([]);
const title = ref("");
const total = ref(0);
const single = ref(true);
const loading = ref(false);
const multiple = ref(true);
const operate = ref("add");
const dateRange = ref([]);
const openAuReq = ref(false);
const openReReq = ref(false);
const openRsReq = ref(false);
const openClReq = ref(false);
const openAdCases = ref(false);
const showSearch = ref(false);
const requirementList = ref([]);

const user = ref(null);

/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/pms/requirement/import/",
});

const columns = ref([
  { key: 0, label: `需求编号`, visible: false },
  { key: 1, label: `需求名称`, visible: true },
  { key: 2, label: `所属产品`, visible: true },
  { key: 3, label: `所属产品`, visible: true },
  { key: 4, label: `需求来源`, visible: true },
  { key: 5, label: `需求分类`, visible: true },
  { key: 6, label: `优先级`, visible: true },
  { key: 7, label: `缺陷数`, visible: true },
  { key: 8, label: `用例数`, visible: true },
  { key: 9, label: `需求状态`, visible: true },
  { key: 10, label: `评审结果`, visible: false },
  { key: 11, label: `关闭类型`, visible: false },
  { key: 12, label: `负责人`, visible: true },
  { key: 13, label: `创建人`, visible: true },
  { key: 14, label: `创建时间`, visible: true },
]);

const data = reactive({
  queryParams: {
    product: route.query.product,
    module: route.query.module,
    page: 1,
    limit: 10,
  },
});

const { queryParams } = toRefs(data);

function isEditButtonDisabled(row) {
  // 检查需求是否已关闭
  if (row.status === "closed") {
    return true;
  }

  // 检查当前用户是否为需求的负责人
  // if (user.value) {
  //   if (row.owner !== user.value) {
  //     return true;
  //   }
  // }
  return false;
}

function editButtonContent(row) {
  // 检查需求是否已关闭
  if (row.status === "closed") {
    return "该需求是已关闭状态，无法进行编辑操作";
  }

  // 检查当前用户是否为需求的负责人
  // if (user.value) {
  //   if (row.owner !== user.value) {
  //     return "您不是该需求的负责人，无法进行编辑操作";
  //   }
  // }
  return "编辑";
}

function isReviewButtonDisabled(row) {
  // 检查需求状态是否为评审中
  if (row.status !== "reviewing") {
    return true;
  }

  // 检查当前用户是否属于需求的评审人员
  // if (user.value) {
  //   if (!row.reviewers.includes(user.value)) {
  //     return true;
  //   }
  // }
  return false;
}

function reviewButtonContent(row) {
  // 检查需求状态是否为评审中
  if (row.status !== "reviewing") {
    return "该需求不是评审中状态，无法进行评审操作";
  }

  // 检查当前用户是否属于需求的评审人员
  // if (user.value) {
  //   if (!row.reviewers.includes(user.value)) {
  //     return "您不是该需求的评审人员，无法进行评审操作";
  //   }
  // }
  return "评审";
}

function isChangeButtonDisabled(row) {
  // 检查需求状态是否为已激活
  if (row.status !== "activated") {
    return true;
  }
  // if (user.value) {
  //   // 检查当前用户是否为需求的负责人
  //   if (row.owner !== user.value) {
  //     return true;
  //   }
  // }
  return false;
}

function changeButtonContent(row) {
  // 检查需求状态是否为已激活
  if (row.status !== "activated") {
    return "该需求不是已激活状态，无法进行变更操作";
  }
  // if (user.value) {
  //   // 检查当前用户是否为需求的负责人
  //   if (row.owner !== user.value) {
  //     return "您不是该需求的负责人，无法进行变更操作";
  //   }
  // }
  return "变更";
}

function isBindingCaseButtonDisabled(row) {
  // 检查当前用户是否为需求的负责人
  // if (user.value) {
  //   if (row.owner !== user.value) {
  //     return true;
  //   }
  // }
  return false;
}

function bindingCaseButtonContent(row) {
  // 检查当前用户是否为需求的负责人
  // if (user.value) {
  //   if (row.owner !== user.value) {
  //     return "您不是该需求的负责人，无法进行添加用例操作";
  //   }
  // }
  return "添加用例";
}

function isCloseButtonDisabled(row) {
  // 检查需求状态是否为已关闭
  if (row.status === "closed") {
    return true;
  }
  // 检查当前用户是否为需求的负责人
  // if (user.value) {
  //   if (row.owner !== user.value) {
  //     return true;
  //   }
  // }
  return false;
}

function closeButtonContent(row) {
  // 检查需求状态是否为已关闭
  if (row.status === "closed") {
    return "该需求是已关闭状态";
  }
  // 检查当前用户是否为需求的负责人
  // if (user.value) {
  //   if (row.owner !== user.value) {
  //     return "您不是该需求的负责人，无法进行关闭操作";
  //   }
  // }
  return "关闭";
}

function isDeleteButtonDisabled(row) {
  // 检查当前用户是否为需求的负责人
  // if (user.value) {
  //   if (row.owner !== user.value) {
  //     return true;
  //   }
  // }
  return false;
}

function deleteButtonContent(row) {
  // 检查当前用户是否为需求的负责人
  // if (user.value) {
  //   if (row.owner !== user.value) {
  //     return "您不是该需求负责人，无法进行删除操作";
  //   }
  // }
  return "删除";
}

/** 查询列表 */
async function getList() {
  loading.value = true;
  try {
    const response = await listRequirement(
      proxy.addDateRange(queryParams.value, dateRange.value)
    );
    requirementList.value = response.data;
    total.value = response.total;

    const userInfo = await useUserStore().getInfo();
    user.value = userInfo.data.user.id;
  } catch (error) {
    console.error("Error fetching data:", error);
  } finally {
    loading.value = false;
  }
}

/** 搜索按钮操作 */
function handleQuery(params = {}) {
  if (params.value) {
    queryParams.value = params.value;
  }
  queryParams.value.page = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  operate.value = "add";
  openAuReq.value = true;
  title.value = "添加需求";
}

/** 修改按钮操作 */
function handleEdit(row) {
  id.value = row.id || ids.value;
  operate.value = "update";
  openAuReq.value = true;
  title.value = "修改需求";
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "需求导入";
  upload.open = true;
}

/** 评审按钮操作 */
function handleReview(row) {
  id.value = row.id || ids.value;
  title.value = "需求评审";
  if (row.status == "reviewing") {
    openReReq.value = true;
  } else {
    openRsReq.value = true;
  }
}

/** 变更操作 */
function handleChange(row) {
  id.value = row.id || ids.value;
  openAuReq.value = true;
  title.value = "变更需求";
  operate.value = "change";
}

/** 关联用例操作 */
function handleBindingCase(row) {
  id.value = row.id || ids.value;
  openAdCases.value = true;
  title.value = "关联用例";
}

/** 关闭操作 */
function handleClose(row) {
  id.value = row.id || ids.value;
  openClReq.value = true;
  title.value = "关闭需求";
}

function handleActive(row) {
  const oldStatus = row.status;
  // 激活需求后，将需求状态重置为 “草稿”，并清空已评审信息
  row.status = "draft";
  row.review_result = "";
  row.closed_type = "";
  updateRequirement(row)
    .then((res) => {
      getList();
      proxy.$modal.msgSuccess("激活成功");
    })
    .catch((error) => {
      row.status = oldStatus;
    });
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    if (row.id) {
      await proxy.$modal.confirm(`确认是否删除 "${row.name}" ？`);
    } else {
      await proxy.$modal.confirm("确认是否删除所有已勾选信息？");
    }
    ids.value = row.id ? [row.id] : ids.value;
    await delRequirement(ids.value);
    proxy.$modal.msgSuccess("删除成功");
    proxy.$refs.tableRef.clearSelection();
    getList();
  } catch (error) {
    console.error(error);
  }
}

/** 添加/修改对象后触发事件 */
function submited() {
  getList();
}

/** Expose方法 */
defineExpose({
  handleQuery,
});

onMounted(() => {
  getList();
});
</script>
